<template>
    <div>
        <el-dialog v-model="props.updateDialog" title="修改客户订单" draggable width="70%" @close="handleClose"
            class="dialogs" @open="handleOpenDialogAdd">
            <el-form :model="AddValue" :rules="rulesAdd" ref="ruleFormRefAdd" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="产品编号" prop="productCode" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.productCode" placeholder="请选择产品" clearable>
                                <template #append>
                                    <el-button :icon="Search" @click="showDialogPro"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品名称" prop="productName" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.productName" placeholder="请选择产品" readonly clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品规格" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.productSpec" placeholder="请选择产品" readonly clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="订单编码" prop="clientOrderCode" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.clientOrderCode" placeholder="请输入订单编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户编码" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.clientCode" placeholder="请选择客户" clearable>
                                <template #append>
                                    <el-button :icon="Search" @click="showDialogCustomer"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="clientName" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.clientName" placeholder="请输入客户名称" readonly clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="订货日期" prop="orderDate" :class="{ 'bold-label': true }">
                            <el-date-picker v-model="AddValue.orderDate" type="date" placeholder="请选择订货日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="交货日期" prop="deliveryDate" :class="{ 'bold-label': true }">
                            <el-date-picker v-model="AddValue.deliveryDate" type="date" placeholder="请选择交货日期" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="订货数量" prop="orderQuantity" :class="{ 'bold-label': true }">
                            <el-input-number v-model="AddValue.orderQuantity" :min="1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位" :class="{ 'bold-label': true }">
                            <el-select v-model="AddValue.unitOfMeasure" placeholder="请选择" style="width: 240px">
                                <el-option v-for="item in props.units" :key="item.id" :label="item.unitName"
                                    :value="item.unitName" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="规格型号" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.spec" placeholder="请输入规格型号" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="质量要求" :class="{ 'bold-label': true }">
                            <el-input v-model="AddValue.qualityRequirement" type="textarea" :rows="2"
                                placeholder="请输入质量要求">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmitAdd(ruleFormRefAdd)">确定</el-button>
                    <el-button type="success" :disabled="GongdDisabled"
                        @click="handleGenerateProductionOrder">生成生产工单</el-button>
                    <el-button @click="Visible">取消</el-button>
                </div>
            </template>
            <div>
                <el-tabs type="border-card" class="shadow-tabs">
                    <el-tab-pane label="物料需求">
                        <el-table :data="materialList" style="width: 100%">
                            <el-table-column type="expand">
                                <template #default="{ row }">
                                    <div class="flex-container">
                                        <p class="flex-item">物料编码: {{ row.itemCode }}</p>
                                        <p class="flex-item">物料名称: {{ row.itemName }}</p>
                                        <p class="flex-item">物料规格: {{ row.specification }}</p>
                                        <template v-for="(warehouse, index) in row.inventory?.warehouseList"
                                            :key="index">
                                            <p class="flex-item">所在仓库: {{ warehouse.warehouseName }}</p>
                                            <p class="flex-item">仓库编码: {{ warehouse.warehouseCode }}</p>
                                        </template>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="层级" align="center">
                                <template #default="{ row }">
                                    <span v-if="row.level == 1">第一层</span>
                                    <span v-if="row.level == 2">第二层</span>
                                    <span v-if="row.level == 3">第三层</span>
                                    <span v-if="row.level == 4">第四层</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="添加物料" align="center">
                                <template #default="{ row }">
                                    <el-button :disabled="row.type" size="large" @click="showDialogWL(row)"><el-icon>
                                            <component :is="CirclePlus" />
                                        </el-icon></el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料名称" prop="itemName" align="center" />
                            <el-table-column label="需求数量" align="center">
                                <template #default="{ row }">
                                    <el-input v-if="isEditing[row.level]" v-model="row.quantity" type="number"
                                        size="large"></el-input>
                                    <span v-else>{{ row.quantity }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存量" align="center">
                                <template #default="{ row }">
                                    <el-tooltip
                                        :content="row.inventory?.inventoryQuantity >= row.quantity ? '库存充足' : '库存不足'"
                                        placement="top">
                                        <span class="slClass">{{ row.inventory?.inventoryQuantity }}</span>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" prop="unitName" align="center" />
                            <el-table-column label="操作" align="center">
                                <template #default="{ row }">
                                    <el-button v-if="!isEditing[row.level]" link size="small"
                                        @click="enterEditMode(row)">编辑</el-button>
                                    <!-- 编辑模式下的保存和取消按钮 -->
                                    <div v-else>
                                        <el-button link size="small" @click="saveChanges(row)">保存</el-button>
                                        <el-button link size="small" @click="cancelEdit(row)">取消</el-button>
                                    </div>
                                    <el-button v-if="!isEditing[row.level]" link size="small"
                                        @click="handleDelete(row)">删除</el-button>
                                </template>

                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <div style="margin-top: 20px;">
                        <el-button type="primary" @click="addNewMaterial" :disabled="isDisabled">新增物料</el-button>
                    </div>
                </el-tabs>
            </div>
        </el-dialog>
        <!-- 产品选择弹窗 -->
        <ProSelectionDialog :ProDialog="dialogVisiblePro" @close-dialog="colseDialog" @rowDataP="rowDataP" />
        <!-- 客户选择弹窗 -->
        <CustomerSelectionDialog :CustomerDialog="dialogVisibleCustomer" @close-dialog="colseDialog"
            @rowDataA="rowData" />
        <!-- 物料选择弹窗 -->
        <WlselectionDialog :WlDialog="dialogVisibleWl" @close-dialog="colseDialog" @rowDataWl="rowDataWl" />
    </div>
</template>

<script setup>
import CustomerSelectionDialog from '@/components/CustomerOrders/CustomerSelectionDialog.vue';
import ProSelectionDialog from '@/components/CustomerOrders/ProSelectionDialog.vue';
import WlselectionDialog from './WlselectionDialog.vue';
import { updateCustomerOrders, insertMaterial, findMaterial, updateQuantity, deleteMaterial, insertProductionOrder, findInventoryById } from '@/apis/lth/index';
import { reactive, ref, nextTick, onMounted, computed, watch } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { Search, CirclePlus } from '@element-plus/icons-vue';
const props = defineProps(['updateDialog', 'units', 'UpdateValue']);
const emit = defineEmits(['close-dialog']);
const dialogVisiblePro = ref(false);//产品选择弹窗
const dialogVisibleCustomer = ref(false);//客户选择弹窗
const dialogVisibleWl = ref(false);//物料选择弹窗
const shadowTabs = ref(false);//物料新增表格
let materialList = ref([]);//物料需求列表
const AddValue = reactive({ ...props.UpdateValue });// console.log("数据：",AddValue)

const showDialogPro = () => {//Go产品选择
    dialogVisiblePro.value = true;
}
const showDialogCustomer = () => {//Go客户选择
    dialogVisibleCustomer.value = true;
}
let currentRow = ref({})
const showDialogWL = (row) => {//GO物料添加
    dialogVisibleWl.value = true;
    currentRow.value = row;
    isEditing[currentRow.value.level] = true;
}

//清空后的表单数据
const ruleFormRefAdd = ref();
//定义响应式对象，用于重置表单
const resetFormAdd = reactive({ ...AddValue });
//验证规则对象
const rulesAdd = {
    productCode: [{
        required: true,//必填项
        message: "产品编号不能为空",//提示错误信息
        trigger: "blur"//触发验证的时机，当失去焦点时触发
    }],
    productName: [{
        required: true,
        message: "产品名称不能为空",
        trigger: "blur"
    }],
    clientOrderCode: [{
        required: true,
        message: "订单编码不能为空",
        trigger: "blur"
    }],
    clientName: [{
        required: true,
        message: "客户名称不能为空",
        trigger: "blur"
    }],
    orderDate: [{
        required: true,
        message: "订货日期不能为空",
        trigger: "blur"
    }],
    deliveryDate: [{
        required: true,
        message: "交货日期不能为空",
        trigger: "blur"
    }],
    orderQuantity: [{
        required: true,
        message: "订货数量不能为空",
        trigger: "blur"
    }],
};
//打开对话框的处理函数
const handleOpenDialogAdd = () => {
    nextTick(() => {
        //清空校验（清空表单校验结果，以便用户重新输入数据）
        ruleFormRefAdd.value.clearValidate();
        findMaterials();
    })
};
const rowData = (row) => {
    console.log("客户数据：", row);
    AddValue.clientId = row.customerId;
    AddValue.clientCode = row.customerCode;
    AddValue.clientName = row.customerName;
}
const rowDataP = (row) => {
    console.log("产品数据：", row);
    AddValue.productId = row.materialNo;
    AddValue.productCode = row.materialProductCode;
    AddValue.productName = row.productName;
    AddValue.productSpec = row.specificationAndModel;
    AddValue.unitOfMeasure = row.unitName;
}
const rowDataWl = (row) => {
    console.log("物料数据", row);
    if (row) {
        currentRow.value.itemCode = row.materialProductCode
        currentRow.value.itemId = row.materialNo
        currentRow.value.itemName = row.productName
        currentRow.value.specification = row.specificationAndModel
        currentRow.value.unitName = row.unitName;
    }
};
const isEditing = reactive([]);//编辑状态
const currentlyEditedRowId = ref(null);
const isInEditMode = computed(() => {
    return Object.values(isEditing).some(editing => editing);
});
const enterEditMode = (row) => {//编辑
    isEditing[row.level] = true;
    currentlyEditedRowId.value = row.itemId;
};
watch(props.UpdateValue, async (newData) => {
    if (newData) {
        Object.assign(AddValue, props.UpdateValue);
    }
});
const saveChanges = (row) => {//保存
    // console.log("保存前行数据：", row);
    if (row.itemCode == null) {
        ElMessage.error('没有选择数据！')
    } else {
        if (!row.type) {
            // Object.assign(AddValue, row);
            AddValue.itemId = row.itemId;
            AddValue.itemCode = row.itemCode;
            AddValue.itemName = row.itemName;
            AddValue.level = row.level;
            AddValue.quantity = row.quantity;
            AddValue.specification = row.specification;
            AddValue.unitName = row.unitName;
            console.log("新增的数据：", AddValue);
            const inventoryList = ref([])
            findInventoryById(AddValue.itemCode).then(res => {
                inventoryList.value = res;
                if (inventoryList.value.length == 0) {
                    ElMessage.error("该物料没有库存，请添加库存");
                    return;
                }
                insertMaterial(AddValue).then(async resp => {
                    if (resp == "成功") {
                        ElMessage.success('新增成功');
                        row.type = true;
                        // console.log("保存后行数据：", row);
                        isEditing[row.level] = false;
                        currentlyEditedRowId.value = null;
                        isAddingMaterial.value = false;
                        await findMaterial(AddValue.clientOrderCode).then(resp => {
                            // console.log("根据物料查询到的库存信息：", resp)
                            materialList.value = resp.map(item => ({
                                ...item,
                                type: true
                            }));
                        })
                    } else {
                        ElMessage.success('新增失败');
                    }
                });
            })
        } else {
            // console.log("修改的数据:",row)
            updateQuantity(row).then(resp => {
                if (resp == "成功") {
                    ElMessage.success("修改成功");
                    isEditing[row.level] = false;
                    currentlyEditedRowId.value = null;
                } else {
                    ElMessage.success("修改失败");
                }
            })
        }
    }
};
const cancelEdit = (row) => {//取消编辑
    if (row.type) {
        isEditing[row.level] = false;
        currentlyEditedRowId.value = null;
    } else {
        ElMessageBox.confirm('有未保存的数据,确定取消吗', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
        }).then(() => {
            const index = materialList.value.indexOf(row);
            if (index !== -1) {
                materialList.value.splice(index, 1);
            }
            isAddingMaterial.value = false;
            isEditing[row.level] = false;
            currentlyEditedRowId.value = null;
        }).catch(() => { });
    }
};
// 创建层物料
const addWL = () => {
    const newRow = {
        level: materialList.value.length + 1,
        type: false,
        itemCode: null,  // 新物料编码
        itemId: null,    // 新物料ID
        itemName: '',
        specification: '',
        quantity: '',    // 数量可以设置为空字符串
        unitName: ''
    };
    materialList.value.push(newRow);
    isAddingMaterial.value = true;
}
const isAddingMaterial = ref(false);
const isDisabled = computed(() => {//新增物料禁用条件
    return (
        materialList.value.length >= 4 ||
        isAddingMaterial.value
    );
});
const GongdDisabled = computed(() => {//生成生产工单禁用条件
    return (
        materialList.value.length === 0
    );
})
// 添加新物料
const addNewMaterial = () => {
    if (!isAddingMaterial.value) {
        if (isInEditMode.value) {
            // ElMessage.warning('每次只能修改一条数据,请保存后再添加');
            ElNotification.warning({
                title: '提示',
                message: '每次只能修改一条数据,请保存后再添加',
                type: 'warning',
            })
        } else {
            addWL();
        }
    }
};
// 删除物料
function handleDelete(row) {
    if (row.type) {
        // console.log("删除的行：",row);
        ElMessageBox.confirm(`是否确认删除物料"${row.itemName}"的数据项？`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deleteMaterial(row.orderItemId).then(res => {
                if (res == "成功") {
                    ElMessage.success("删除成功");
                    findMaterials();
                } else {
                    ElMessage.error("删除失败")
                }
            })
        }).catch(() => {
            // ElMessage.info('已取消删除')
        })
    } else {
        const index = materialList.value.indexOf(row);
        if (index !== -1) {
            materialList.value.splice(index, 1);
        }
        isAddingMaterial.value = false;
    }
};
const findMaterials = async () => {
    await findMaterial(AddValue.clientOrderCode).then(res => {
        materialList.value = res;
        materialList.value.forEach(item => {
            item.type = true
        })
    })
};
onMounted(() => {
    findMaterials();
})
//确认提交事件
const handleSubmitAdd = (value) => {
    value.validate(valid => {
        if (valid) {
            updateCustomerOrders(AddValue).then(res => {
                if (res == '成功') {
                    ElMessage.success('修改成功');
                } else {
                    ElMessage.error("修改失败")
                }
            });
        } else {
            ElMessage.error("请根据提示填写完整数据")
        }
    })
};
const handleGenerateProductionOrder = () => {//生成生产工单
    let ordercode = createID();//工单编码生成
    // console.log("生成工单编码：", ordercode)
    if (!materialList.value.length) {
        ElMessage.error("未添加物料需求数据的客户订单,不允许生成生产订单")
    } else {
        ElMessageBox.confirm('操作生成生产工单后,当前订单会锁定,不能继续修改,是否确认生成订单?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const proWorkorder = {
                workorderCode: ordercode,
                workorderName: AddValue.productName,
                clientOrderId: AddValue.clientOrderId,//客户订单编码
                clientOrderCode: AddValue.clientOrderCode,
                orderSource: 'ORDER',//来源类型：ORDER客户订单
                sourceCode: AddValue.clientOrderCode,//来源单据（客户订单编码）
                productId: AddValue.productId,
                productCode: AddValue.productCode,
                productName: AddValue.productName,
                productSpec: AddValue.productSpec,
                unitOfMeasure: AddValue.unitOfMeasure,
                quantity: AddValue.orderQuantity,//工单数量
                clientId: AddValue.clientId,
                clientCode: AddValue.clientCode,
                clientName: AddValue.clientName,
                requestDate: AddValue.deliveryDate,//需求日期
                parentId: 0,//父工单
                ancestors: '0',//所有父节点ID
                status: 'PREPARE', //单据状态：默认草稿
                workorderType: 'SELF',//工单类型：默认自产
            }; //console.log(proWorkorder);

            insertProductionOrder(proWorkorder).then(resp => {//成功生成工单后
                // console.log("添加的工单Id", resp)
                AddValue.workorderId = resp;
                const value = {
                    workorderId: AddValue.workorderId,
                    workorderCode: ordercode,
                    workorderName: AddValue.productName,
                    clientOrderId: AddValue.clientOrderId,
                    status: 'WORK_ORDER_FINISHED',
                }; //console.log(value)

                updateCustomerOrders(value).then(resp => {//对订单主表进行更新（加入工单信息）
                    if (resp == "成功") {
                        console.log("订单单据状态修改成功")
                    } else {
                        console.log("订单单据状态修改失败")
                    }
                })
                emit('close-dialog');//关闭
                // ElMessageBox.confirm(`生成生产工单成功,订单编码:${ordercode},是否跳转到生产工单页面?`, '系统提示', {
                //     confirmButtonText: '确定',
                //     cancelButtonText: '取消',
                //     type: 'warning'
                // }).then(() => {

                // }).catch(() => {
                //     // ElMessage.info("成功取消");
                // })
            })
        }).catch(() => {
            // ElMessage.info("成功取消");
        })
    }
};
function createID() {//工单编码生成
    let code = 'MO';
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    code = code + year + month + strDate + Math.floor(Math.random() * 10000);
    return code;
};
//关闭弹窗
const handleClose = () => {
    Object.assign(AddValue, resetFormAdd)
    emit('close-dialog');
    shadowTabs.value = false;
};
//弹窗取消事件
const Visible = () => {
    emit('close-dialog');
};
//关闭弹窗事件
const colseDialog = async () => {
    dialogVisibleCustomer.value = false;
    dialogVisiblePro.value = false;
    dialogVisibleWl.value = false;
};
</script>

<style scoped>
.flex-container {
    display: flex;
    align-items: center;
    gap: 16px;
    /* 16px 的水平间距 */
}

.flex-item {
    margin-bottom: 8px;
    /* 底部间距 */
}

.shadow-tabs {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;
}

.slClass {
    background-color: #e8f4ff;
    border-color: #d1e9ff;
    display: inline-block;
    padding: 0 10px;
    line-height: 30px;
    font-size: 12px;
    color: #1890ff;
    border-width: 1px;
    border-style: solid;
    border-radius: 4px;
}
</style>
